package com.xp.tinyurl.common.utils;

/**
 * @author xp
 * @discription 进制转换类
 * @since 2.0.0
 */
public class BinaryUtil {

    private static final String CHARS = "0wxWXYZ1BtuvIJyzAMdUV8FGH6ks7nop45NlmCbcjOefghQRS93iTDEqaKL2rP_-";

    private static final long BINARY_62 = 64L;

    /**
     * 十进制转换62进制
     *
     * @param decimal 要转换的十进制数
     * @return 62进制
     */
    public static String convertDecimalTo62(long decimal) {
        StringBuilder sb = new StringBuilder();
        int remainder;

        while (decimal > BINARY_62 - 1) {
            remainder = (int) (decimal % BINARY_62);
            sb.append(CHARS.charAt(remainder));
            decimal = decimal / BINARY_62;
        }

        sb.append(CHARS.charAt((int) decimal));
        return sb.reverse().toString();
    }

    public static long toBase10(String str) {
        //从右边开始
        return toBase10(new StringBuilder(str).reverse().toString().toCharArray());
    }

    private static long toBase10(char[] chars) {
        long n = 0;
        int pow = 0;
        for (char item : chars) {
            n += toBase10(CHARS.indexOf(item), pow);
            pow++;
        }
        return n;
    }

    private static long toBase10(int n, int pow) {
        return n * (long) Math.pow(BINARY_62, pow);
    }
}
